﻿using CSRedis;
using Ocelot.Cache;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using SX.Core;

namespace SX.GateWay
{
    /// <summary>
    /// 重写Ocelote默认缓存采用redis
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RedisCache<T>: IOcelotCache<T>
    {
        private readonly Appsettings _appsettings;
        public RedisCache(Appsettings appsettings)
        {
            _appsettings = appsettings;
            CSRedisClient csredis;
            if (appsettings.RedisConns.Count == 1)
            {
                //普通模式
                csredis = new CSRedis.CSRedisClient(appsettings.RedisConns[0]);
            }
            else
            {
                //集群模式
                //实现思路：根据key.GetHashCode() % 节点总数量，确定连向的节点
                //也可以自定义规则(第一个参数设置)
                csredis = new CSRedis.CSRedisClient(null, appsettings.RedisConns.ToArray());
            }
            //初始化 RedisHelper
            RedisHelper.Initialization(csredis);
        }

        public void Add(string key, T value, TimeSpan ttl, string region)
        {
            key = GetKey(region, key);
            if (ttl.TotalMilliseconds <= 0)
            {
                return;
            }
            RedisHelper.Set(key, value.To_Json(), (int)ttl.TotalSeconds);
        }

        public void AddAndDelete(string key, T value, TimeSpan ttl, string region)
        {
            Add(key, value, ttl, region);
        }

        public void ClearRegion(string region)
        {
            throw new NotImplementedException();
        }

        public T Get(string key, string region)
        {
            key = GetKey(region, key);
            var result = RedisHelper.Get(key);
            if (!String.IsNullOrEmpty(result))
            {
                return JsonConvert.DeserializeObject<T>(result);
            }
            return default(T);
        }
        private string GetKey(string region, string key)
        {
            return _appsettings.RedisKeyPrefix + ":" + region + ":" + key;
        }
    }
}
